package com.Nuyoah.demo01.service;

import com.Nuyoah.demo01.common.JsonResult;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.Map;
import java.util.Iterator;
@Service
public class CaptchaService {
    // 使用 ConcurrentHashMap 存储 Session ID 和验证码值，以及最后访问时间
    private static final ConcurrentHashMap<String, CaptchaEntry> captchaMap = new ConcurrentHashMap<>();

    // 定时任务线程池
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    // 验证码过期时间，单位为毫秒
    private static final int CAPTCHA_EXPIRATION_TIME = 5 * 60 * 1000;
    // 启动定时任务，每分钟检查一次过期键值对
    static {
        scheduler.scheduleAtFixedRate(() -> {
            long currentTime = System.currentTimeMillis();
            Iterator<Map.Entry<String, CaptchaEntry>> iterator = captchaMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, CaptchaEntry> entry = iterator.next();
                CaptchaEntry captchaEntry = entry.getValue();
                if (currentTime - captchaEntry.getTimestamp() > CAPTCHA_EXPIRATION_TIME) {
                    iterator.remove();
                    System.out.println("Removed expired captcha for session ID: " + entry.getKey());
                }
            }
        }, 0, 1, TimeUnit.MINUTES);
    }

    // 生成验证码并返回验证码的 Base64 图片和 Session ID
//    public Map<String, String> generateCaptcha() {

    public JsonResult<Map<String, String>> generateCaptcha() {

        // 获取当前请求的 Session
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();

        // 创建一个算术验证码对象
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48, 2);
        String captchaText = captcha.text();
        if (captchaText == null || captchaText.isEmpty()) {
            throw new IllegalStateException("Captcha text is empty.");
        }

        // 将验证码的答案存入 session
        session.setAttribute("captcha", captchaText);

        // 更新或插入键值对到 captchaMap
        String sessionId = session.getId();
        captchaMap.put(sessionId, new CaptchaEntry(captchaText, System.currentTimeMillis()));

        // 打印日志
        System.out.println("Generated captcha for session ID: " + sessionId + ", captcha text: " + captchaText);

        // 返回验证码的 Base64 图片和 Session ID
        Map<String, String> result = new HashMap<>();
        result.put("captchaImage", captcha.toBase64());
        result.put("sessionId", sessionId);

        //新增
        // 假设 captchaService.generateCaptcha() 返回一个 Map<String, String>，包含 captchaImage 和 sessionId
        if (result == null || !result.containsKey("captchaImage") || result.get("captchaImage").isEmpty()) {
            return new JsonResult<>("1", "验证码生成失败");
        }

        return new JsonResult<>("200", result, "验证码生成成功");
    }


    // 验证验证码
    public boolean validateCaptcha(String userInput, String sessionId) {
        System.out.println("Validating captcha for session ID: " + sessionId + ", user input: " + userInput);

        // 从全局 Map 中获取验证码值
        CaptchaEntry captchaEntry = captchaMap.get(sessionId);
        if (captchaEntry == null) {
            System.out.println("No captcha found for session ID: " + sessionId);
            return false;
        }

        // 更新最后访问时间
        captchaMap.put(sessionId, new CaptchaEntry(captchaEntry.getCaptchaText(), System.currentTimeMillis()));

        // 验证用户输入
        boolean isValid = captchaEntry.getCaptchaText().equalsIgnoreCase(userInput);

        // 验证成功后，移除验证码值
        if (isValid) {
            captchaMap.remove(sessionId);
            System.out.println("Captcha validated successfully for session ID: " + sessionId + ", captcha text: " + captchaEntry.getCaptchaText());
        } else {
            System.out.println("Captcha validation failed for session ID: " + sessionId + ", captcha text: " + captchaEntry.getCaptchaText());
        }

        return isValid;
    }

    // 内部类，用于存储验证码值和最后访问时间
    private static class CaptchaEntry {
        private final String captchaText;
        private final long timestamp;

        public CaptchaEntry(String captchaText, long timestamp) {
            this.captchaText = captchaText;
            this.timestamp = timestamp;
        }

        public String getCaptchaText() {
            return captchaText;
        }

        public long getTimestamp() {
            return timestamp;
        }
    }
}